package com.example.insectmanagementsystem.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.insectmanagementsystem.pojo.Insect;
import com.example.insectmanagementsystem.pojo.InsectCategory;

import com.example.insectmanagementsystem.service.InsectCategoryService;
import com.example.insectmanagementsystem.service.InsectService;
import org.junit.platform.commons.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Controller
public class InsectController {
    @Autowired
    private InsectService insectService;

    @Autowired
    private InsectCategoryService insectCategoryService;

    @GetMapping("/list")
    public String list(Model model, Insect insect) {
        List<InsectCategory> insectCategories = insectCategoryService.list();

        // 获取查询条件
        String name = insect.getName();
        Integer cid = insect.getCid();

        // 构建查询条件
        QueryWrapper<Insect> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(name)) {
            queryWrapper.like("name", name);
        }
        if (cid != null) {
            queryWrapper.eq("cid", cid);
        }

        // 执行查询
        List<Insect> insects = insectService.list(queryWrapper);

        model.addAttribute("insectCategories", insectCategories);
        model.addAttribute("insects", insects);

        return "list";
    }

    @GetMapping("/toAdd")
    public String toAdd(Model model) {
        List<InsectCategory> insectCategories = insectCategoryService.list();

        model.addAttribute("insectCategories", insectCategories);

        return "add";
    }

    @PostMapping("/add")
    public String add(Insect insect) {
        boolean result = insectService.save(insect);
        if (result) {
            return "redirect:/list";
        } else {
            return "error";
        }
    }

    @GetMapping("/del")
    public String del(@RequestParam Integer id){
        boolean result = insectService.removeById(id);
        if (result){
            return "1";
        }else {
            return "0";
        }
    }
}
